<template>
  <div>
    <el-dialog v-for="dialog in dialogList"
      v-scrollClose
      :ref="dialog.key"
      :key="dialog.key"
      :visible.sync="dialog.show"
      :title="dialog.meta.title"
      :width="getDialogWidth(dialog)"
      :class="{
        'dialog_globalAlert': dialog.meta.dialogType === 'globalAlert',
        'login_timeout_dialog': dialog.meta.dialogType === 'loginTimeout',
        'dialog_bodyNoPadding': dialog.meta.bodyNoPadding
      }"
      :close-on-click-modal="dialog.meta.closeOnClickModal === true"
      :close-on-press-escape="false"
      :show-close="dialog.meta.showClose !== false"
      :custom-class="dialog.meta.customClass"
      @close="close(dialog)">
      <!-- <div style="overflow: hidden;" -->
      <div class="dialog_globalAlert_headerImg"
        v-if="dialog.meta.dialogType === 'globalAlert'">
        <i class="icon iconfont icon-kefu"></i>
      </div>
      <div class="dialog_globalAlert_headerText"
        v-if="dialog.meta.dialogType === 'globalAlert'">
        {{ $t('Layout.globalAlert.friendlyTips') }}
      </div>
      <div :style="getDialogStyle(dialog)">
        <dialog-render v-if="dialog.render"
          :key="dialog.key"></dialog-render>
      </div>
      <div v-if="dialog.meta.isShowFooter !== false"
        :class="footeralign(dialog.meta.footerAlign)"
        slot="footer"
        class="dialog-footer ovf-hd">
        <div class="fl tx-l"
          v-if="dialog.meta.footerTxt">{{ dialog.meta.footerTxt }}</div>
        <div class="fl tx-l"
          v-else-if="dialog.meta.footerHtml"
          v-html="dialog.meta.footerHtml"></div>
        <div v-else-if="dialog.meta.footerRender && dialog.render">
          <dialog-footer-render :key="dialog.key"></dialog-footer-render>
        </div>
        <div class="fl">
          <div v-if="dialog.meta.customButtonText && dialog.meta.isShowCustomButton"
               @click="customButton(dialog)"
               class="dialog-custom-button"
               >
            <i class="icon iconfont icon-binghangwangguan"></i>
            <span>{{ dialog.meta.customButtonText}}</span>
          </div>
        </div>
        <el-button v-if="dialog.meta.isShowCancelBtn !== false"
          @click="cancel(dialog)"
          size="mini"
          plain
          :loading="dialog.cancelBtnLoading">
          {{ dialog.meta.cancelBtnTxt || $t('Layout.dialogManager.cancel') }}
        </el-button>
        <el-button v-if="dialog.meta.isShowConfirmBtn !== false"
          type="primary"
          size="mini"
          style="margin-left:10px"
          @click="confirm(dialog)"
          :disabled="dialog.confirmBtnLoading"
          :loading="dialog.confirmBtnLoading">
          {{ dialog.meta.confirmBtnTxt || $t('Layout.dialogManager.confirm') }}
        </el-button>
      </div>
      <div v-if="dialog.meta.dialogType === 'globalAlert' && dialog.meta.globalAlertConfig.buttons"
        slot="footer"
        class="dialog-footer ovf-hd dialogFooter_globalAlert">
        <template v-for="(button, index) in dialog.meta.globalAlertConfig.buttons || []">
          <el-button :key="index*index"
            :type="button.type"
            :plain="button.isPlain"
            @click="button.callback({ vm, dialog })">
            {{ button.name ? button.name : $t(button.i18nName) }}
          </el-button>
        </template>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Vue from 'vue'
export default {
  name: 'dialogManager',
  directives: {
    scrollClose: {
      bind(el, binding, vnode) {
        function closeSelect(e) {
          if (
            e.target.className === 'el-select-dropdown__item' ||
            e.target.className === 'el-select-dropdown__item hover'
          ) {
          } else {
            const selectDom = document.querySelectorAll('.el-select')
            for (let i = 0; i < selectDom.length; i++) {
              selectDom[i]['@@clickoutsideContext'].bindingFn() // 借用clickoutsideContext的指令绑定的函数去实现关闭
            }
          }
        }
        // 为当前元素绑定私有变量，方便解除监听事件
        el.__vueCloseSelect__ = closeSelect
        el.addEventListener('mousewheel', closeSelect, false)
      },
      unbind(el, binding, vnode) {
        // dom不存在时，解除事件绑定
        el.removeEventListener('mousewheel', el.__vueCloseSelect__)
        delete el.__vueCloseSelect__
      }
    }
  },
  data() {
    return {
      // 是否由取消按钮触发close事件
      closeByCancel: false,
      vm: this
    }
  },
  computed: {
    dialogList() {
      return (
        (this.$store.state.dialogManager &&
          this.$store.state.dialogManager.dialogList) ||
        []
      )
    },
    dialogBodySize() {
      return ''
    }
  },
  created() {
    const self = this
    Vue.component('dialog-render', {
      functional: true,
      props: {
        // ...
      },
      render(h, context) {
        let currentDialog = null
        const component = null
        const key = context.data.key
        const attrs = {
          'data-dialogkey': key
        }
        self.dialogList.forEach(dialog => {
          if (dialog.key === key) {
            currentDialog = dialog
            return false
          }
        })
        const children = []
        if (currentDialog) {
          return h(currentDialog.component, {
            ref: `dialogBody_${currentDialog.key}`,
            attrs,
            props: currentDialog.props,
            on: currentDialog.events
          })
        }
        return h('div')
      }
    })

    Vue.component('dialog-footer-render', {
      functional: true,
      props: {
        // ...
      },
      render(h, context) {
        let currentDialog = null
        // let component = null
        const footerEmitBody = self.footerEmitBody
        const key = context.data.key
        const attrs = {
          'data-dialogkey': key
        }
        self.dialogList.forEach(dialog => {
          if (dialog.key === key) {
            currentDialog = dialog
            return false
          }
        })
        const children = []
        if (currentDialog) {
          return h(currentDialog.meta.footerRender, {
            ref: `dialogFooterRender_${currentDialog.key}`,
            props: { ...currentDialog.props, dialogKey: currentDialog.key },
            on: { ...currentDialog.events, footerEmitBody },
            attrs
          })
        }
        return h('div')
      }
    })
  },
  methods: {
    getDialogStyle(dialog) {
      if (dialog.meta.bodyHeight < 150) {
        dialog.meta.bodyHeight = 150
      } else if (dialog.meta.bodyHeight > 570) {
        dialog.meta.bodyHeight = 570
      }
      if (dialog.meta.minHeightStatus) {
        return {
          minHeight: dialog.meta.bodyHeight + 'px',
          maxHeight: '570px'
        }
      } else {
        return {
          height: dialog.meta.bodyHeight + 'px'
        }
      }
    },
    getDialogWidth(dialog) {
      if (dialog.meta.width) {
        return dialog.meta.width + 'px'
      } else {
        switch (dialog.meta.size) {
          case 'small':
            return '500px'
          case 'normal':
            return '700px'
          case 'large':
            return '900px'
          default:
            return '700px'
        }
      }
    },
    footeralign(type) {
      if (type) {
        switch (type) {
          case 'center':
            return 'dialog-footer-center'
          case 'left':
            return 'dialog-footer-left'
          case 'right':
            return 'dialog-footer-right'
          default:
            return ''
        }
      }
      return ''
    },
    customButton(dialog) {
      if (
        this.$refs[`dialogBody_${dialog.key}`] &&
        this.$refs[`dialogBody_${dialog.key}`].customButton &&
        this.$refs[`dialogBody_${dialog.key}`].customButton instanceof Function
      ) {
        this.$refs[`dialogBody_${dialog.key}`].customButton()
      }
    },
    confirm(dialog) {
      if (
        this.$refs[`dialogBody_${dialog.key}`] &&
        this.$refs[`dialogBody_${dialog.key}`].confirm &&
        this.$refs[`dialogBody_${dialog.key}`].confirm instanceof Function
      ) {
        this.$refs[`dialogBody_${dialog.key}`].confirm()
      }
    },
    cancel(dialog) {
      this.closeByCancel = true
      if (
        this.$refs[`dialogBody_${dialog.key}`] &&
        this.$refs[`dialogBody_${dialog.key}`].cancel &&
        this.$refs[`dialogBody_${dialog.key}`].cancel instanceof Function
      ) {
        this.$refs[`dialogBody_${dialog.key}`].cancel()
      }
    },
    close(dialog) {
      this.$emit('close')
      if (this.closeByCancel) {
        this.closeByCancel = false
        return
      }
      this.$store.dispatch('dialogManager/closeDialog', dialog.key)
      if (
        this.$refs[`dialogBody_${dialog.key}`] &&
        this.$refs[`dialogBody_${dialog.key}`].cancel &&
        this.$refs[`dialogBody_${dialog.key}`].cancel instanceof Function
      ) {
        this.$refs[`dialogBody_${dialog.key}`].cancel()
      }
    },
    footerEmitBody(dialogKey, callback) {
      console.log('footerEmitBody')
      if (
        this.$refs[`dialogBody_${dialogKey}`] &&
        this.$refs[`dialogBody_${dialogKey}`].footerEmitBody &&
        this.$refs[`dialogBody_${dialogKey}`].footerEmitBody instanceof Function
      ) {
        this.$refs[`dialogBody_${dialogKey}`].footerEmitBody(callback)
      }
    }
  }
}
</script>

<style lang="less">
.dialog_globalAlert {
  .dialog_globalAlert_headerImg,
  .dialog_globalAlert_headerText {
    position: absolute;
    left: 50%;
    color: @primaryColor;
    transform: translateX(-50%);
  }
  .dialog_globalAlert_headerImg {
    top: -90px;
    font-size: 58px;
    i {
      font-size: 58px;
    }
  }
  .dialog_globalAlert_headerText {
    top: -15px;
    font-size: 18px;
  }
  .el-dialog__header {
    padding: 0;
    height: 125px;
    border-bottom: none;
    background-color: #fff;
    background-image: url('../../assets/images/common/globalAlertHeader.png');
    .el-dialog__headerbtn {
      top: 15px;
      right: 15px;
      line-height: 1;
    }
  }
  .el-dialog__body {
    overflow-y: visible;
    padding-top: 32px;
  }
  .el-dialog__footer {
    padding: 0;
    border-top: none;
  }

  .dialogFooter_globalAlert {
    padding-bottom: 30px;
    text-align: center;
    .el-button {
      padding-top: 0;
      padding-bottom: 0;
      min-width: 90px;
      height: 36px;
      border-radius: 2px;
      line-height: 36px;
      & + .el-button {
        margin-left: 20px;
      }
    }
  }
  .dialog_globalAlert_title {
    margin-bottom: 8px;
    // color: #333333;
    color: #262626;
    font-weight: bold;
    // font-size: 14px;
    font-size: 16px;
    line-height: 1.4;
  }
  .dialog_globalAlert_content {
    // color: #999999;
    color: #8C8C8C;
    font-size: 14px;
    line-height: 1.4;
  }
}

.login_timeout_dialog {
  .el-dialog__header {
    display: none;
  }
  .el-dialog__body {
    height: 360px;
    padding: 0px;
    overflow: hidden;
  }
  .el-dialog__footer {
    display: none;
  }
}

.dialog_bodyNoPadding {
  .el-dialog__body {
    padding: 0;
  }
}
.dialog-custom-button{
  width: 90px;
  height: 28px;
  font-size: 14px;
  font-weight: 400;
  color: #FF884D;
  line-height: 28px;
  cursor: pointer;
  i{
    font-size:12px;
  }
}
</style>
